package com.trsj.lnsj.util;

import java.io.File;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiNiu {
    private static Logger logger = LoggerFactory.getLogger(QiNiu.class);
    // AK/SK 存储空间名称
    public static final String ACCESS_KEY = "7otc0ZMHBLH9tsR0cS3KPoHxMn6bvXVhh_0kJ_Ol";
    public static final String SECRET_KEY = "7vNXWvMxr7g1PlZ7_6Uw_m29cuGMbNbi-940KIbo";
    // 存储空间名
    public static final String bucket = "happyrepo"; // 七牛云空间存储空间名称(存图片)
    public static final String bucket1 = "documentfile";// 七牛云空间存储空间名称(存文档)

    public static String token(String bucketName) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(bucketName);
        return upToken;
    }

    /**
     * 默认存储空间
     * 
     * @return
     */
    public static String token() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(bucket);
        return upToken;
    }

    /**
     * 上传一个文件（传文件路径)
     * 
     * @param filePath
     * @param fileName
     * @return
     */
    public static String uploadFile(String filePath, String fileName, String bucketName, int zoneName) {
        try {
            Zone zone = Zone.zone0();
            if (zoneName == 0) { // 华南
                zone = Zone.zone0();
            }
            if (zoneName == 1) { // 华北
                zone = Zone.zone1();
            }
            if (zoneName == 2) { // 华东
                zone = Zone.zone2();
            }

            Configuration cfg = new Configuration(zone);
            UploadManager uploadManager = new UploadManager(cfg);
            Response response = uploadManager.put(filePath, fileName, token(bucketName));
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.info(fileName + "----文件上传失败----" + r.toString());
            try {
                System.err.println(r.bodyString());
                logger.info(fileName + "----文件上传失败----" + r.toString());
            } catch (QiniuException ex2) {
                // ignore
            }
            return null;
        }
    }

    /**
     * 上传一个文件(传文件)
     * 
     * @param filePath
     * @param fileName
     * @return
     */
    public static String uploadFile(File file, String fileName, String bucketName, int zoneName) {
        try {
            Zone zone = Zone.zone0();
            if (zoneName == 0) { // 华南
                zone = Zone.zone0();
            }
            if (zoneName == 1) { // 华北
                zone = Zone.zone1();
            }
            if (zoneName == 2) { // 华东
                zone = Zone.zone2();
            }

            Configuration cfg = new Configuration(zone);
            UploadManager uploadManager = new UploadManager(cfg);
            Response response = uploadManager.put(file, fileName, token(bucketName));
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.info(fileName + "----文件上传失败----" + r.toString());
            try {
                System.err.println(r.bodyString());
                logger.info(fileName + "----文件上传失败----" + r.toString());
            } catch (QiniuException ex2) {
                // ignore
            }
            return null;
        }
    }

    /**
     * 上传一个字符串
     * 
     * @param uploadString
     * @param key
     * @return
     */
    public static String uploadByte(String uploadString, String key, int zoneName) {
        try {
            byte[] uploadBytes = uploadString.getBytes("utf-8");
            try {
                Zone zone = Zone.zone0();
                if (zoneName == 0) { // 华南
                    zone = Zone.zone0();
                }
                if (zoneName == 1) { // 华北
                    zone = Zone.zone0();
                }
                if (zoneName == 2) { // 华东
                    zone = Zone.zone0();
                }
                Configuration cfg = new Configuration(zone);
                UploadManager uploadManager = new UploadManager(cfg);
                Response response = uploadManager.put(uploadBytes, key, token());
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);

                return putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                logger.info(uploadString + "----上传失败----" + r.toString());
                try {
                    System.err.println(r.bodyString());
                    logger.info(uploadString + "----上传失败----" + r.toString());
                } catch (QiniuException ex2) {
                    // ignore
                }
                return null;
            }
        } catch (UnsupportedEncodingException ex) {
            // ignore
            return null;
        }
    }

    /**
     * 根据Key值删除云端文件
     * 
     * @param key
     */
    /*public static Boolean deleteFile(String key) {
        Configuration cfg = new Configuration(Zone.zone2());
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            Response result = bucketManager.delete(bucket, key);
            System.err.println(new Gson().toJson(result));
            if (result.statusCode == 200) {
                return true;
            }
        } catch (QiniuException ex) {
            // 如果遇到异常，说明删除失败
            logger.info(key + "----删除失败----" + ex.code());
            logger.info(key + "----删除失败----" + ex.response.toString());
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
        return false;
    }*/
    
    public static void main(String[] args) {
        String filePath="C:\\Users\\winte\\Pictures\\3.jpg";
        File ss = new File(filePath);
        String fileName = "3.jpg";
        String result = QiNiu.uploadFile(ss, fileName, QiNiu.bucket, 2);
        System.err.println(result);
    }
}
